package com.example.nio.config;

import cn.hutool.json.JSONUtil;
import com.example.nio.commons.ChatMessage;
import com.example.nio.service.MessageDisposeService;
import com.example.nio.utils.AgentUserUtil;
import com.example.nio.utils.AssignedUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

@Configuration
public class MessageSendService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${spring.rabbitmq.directexchange}")
    private String exchangeName;

    @Value("${spring.rabbitmq.directrouting}")
    private String routingName;

    @Autowired
    private FlowNumHandler flowNumHandler;

    public void sendMessage(ChatMessage chatMessage){
        try {
            //发布mq
            rabbitTemplate.convertAndSend(exchangeName, routingName, JSONUtil.toJsonStr(chatMessage));
            flowNumHandler.put(UUID.randomUUID().toString(),chatMessage);
            //wxService.getWxMessage(wxMessage);
        } catch (Exception e) {
            messageProcessingFailure(chatMessage);
        }
    }

    public void messageProcessingFailure(ChatMessage chatMessage) {
        AssignedUtil.disconnect(chatMessage.getFromUser());
        AgentUserUtil.deleteUser(chatMessage.getFromUser());
        System.out.println("处理微信异常失败");
    }
}
